package com.ellecity06.cwhiskymall.ui.calssify

import androidx.lifecycle.viewModelScope
import com.ellecity06.common.base.BaseMviViewModel
import com.ellecity06.common.ktx.postEvent
import com.ellecity06.cwhiskymall.bean.request.ClassifyRightRequest
import com.ellecity06.cwhiskymall.bean.response.ClassifyResponse
import com.ellecity06.cwhiskymall.http.request
import kotlinx.coroutines.launch

/**
 * @author ellecity06
 * @time 2024/10/22 14:49
 * @des
 */
class ClassifyViewModel : BaseMviViewModel<ClassifyState, ClassifyIntent>() {
    var classifyData: List<ClassifyResponse>? = null
    override suspend fun collectIntent(it: ClassifyIntent) {
        when (it) {
            // 获取顶部内容
            is ClassifyIntent.getCagetoryList -> getCagetoryList()
            is ClassifyIntent.getLeftCatetoryList -> {
                var list = classifyData?.filter { l -> l.id == it.id }
                if (!list.isNullOrEmpty()) {
                    mState.postEvent(ClassifyState.ClassifyLeftData(list[0].children))
                }
            }
            is ClassifyIntent.getClassifyRightList -> {
                if (!it.isLoad) {
                    pagerHelper.pageIndex = 1
                }
                getCagetoryGoods(it.categoryId)
            }
            is ClassifyIntent.showDialog -> {
                if (!classifyData.isNullOrEmpty()) {
                    mState.postEvent(ClassifyState.showDialog(classifyData))
                }
            }
            else -> {}
        }
    }


    private fun getCagetoryList() {
        request(api = { getCagetoryList() }, success = {
            if (it != null) {
                classifyData = it
                mState.postEvent(ClassifyState.ClassifyTopData(it))
            }
        }, error = {
            viewModelScope.launch { mState.postEvent(ClassifyState.Error) }
        })
    }

    private fun getCagetoryGoods(categoryId: Int) {
        var request = ClassifyRightRequest(categoryId)
        request.pageNum = pagerHelper.pageIndex
        request.pageSize = pagerHelper.pageSize
        request(api = { getClassifyRightList(request) }, success = {
            if (it != null) {
                if (!it.records.isNullOrEmpty()) {
                    if (pagerHelper.pageIndex == 1) {
                        val hasMore = it.records!!.size >= request.pageSize
                        mState.postEvent(ClassifyState.RefreshGoods(it.records!!, hasMore))
                    } else {
                        val hasMore = it.records!!.size >= request.pageSize
                        mState.postEvent(ClassifyState.LoadMoreGoods(it.records!!, hasMore))
                    }
                    pagerHelper.pageIndex++
                } else {
                    mState.postEvent(ClassifyState.noMoreData)
                }
            }
        }, error = {
            viewModelScope.launch { mState.postEvent(ClassifyState.Error) }
        })
    }


}